import configparser
from configparser import Interpolation
from functools import wraps
from utils import *

class VimMappingManger():
    def __init__(self,result_path=None,replace_str="{abs_op}"):
        self.config = self._getConfigParser()
        self.result_path=result_path
        if self.result_path is None:
           self.result_path='.mapping.vim'
        self.replace_str=replace_str

    def _getConfigParser(self):
        return configparser.ConfigParser(interpolation=Interpolation())

    @errorWrap
    def import_mapping_file(self,filepath):
        if len(self.config.sections())==0:
           self.config.read(filepath)
        else :
            change_config=self._getConfigParser()
            change_config.read(filepath)
            for section in change_config.sections():
                if self.config[section] is None:
                    self.config[section]={}
                for key in change_config[section]:
                    self.config[section][key]=change_config[section][key]

    @errorWrap
    def import_function(self,filepath):
        function=self._getConfigParser()
        function.read(filepath)
        with open(self.result_path,'w') as f:
            for section in function.sections():
                lose_section=False
                temp_list=[]
                temp_list.append(f'"section:{section}:------\n')
                if  not self.config.has_section(section) or self.config[section] is None :
                    lose_section = True
                elif self.config.has_option(section,'mapleader') :
                    mapleader=self.config[section]['mapleader']
                    temp_list.append(f'let mapleader_temp=mapleader\n')
                    if not mapleader is None:
                        temp_list.append(f'let mapleader={ repr(mapleader) }\n')


                for key in function[section]:
                    cmd_sample=function[section][key]
                    #  print(f'section \n {key}:{cmd_sample}')
                    if lose_section or self.config[section][key] is None:
                        temp_list.append('"lose :'+cmd_sample+'\n')
                    else:
                        cmd=cmd_sample.replace(self.replace_str,self.config[section][key],1)
                        temp_list.append(cmd+'\n')
                temp_list.append(f'let mapleader=mapleader_temp\n')

                f.writelines(temp_list)
        vim.command(f'let g:python_mapping_result_file={repr(self.result_path)}')
        vim.command(f'source {self.result_path}')

    def clear_mapping(self):
        self.config.clear()

if __name__=='__main__':
    if False:
        debug=vim.eval('g:python_debug')
    else :
        debug=0
        vim.command(f"let g:python_debug=0")
    if  int(debug) or not 'vim_mapping_custom' in globals():
        print(f"debug={debug}")
        from tempfile import NamedTemporaryFile

        vim_mapping_custom=VimMappingManger(result_path=NamedTemporaryFile('w+t').name)

